package com.jstyle.jclifexd.activity;

import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.adapter.TempHistoryDetailAdapter;
import com.jstyle.jclifexd.adapter.TempTotalAdapter;
import com.jstyle.jclifexd.daoManager.HealthDataDaoManager;
import com.jstyle.jclifexd.daoManager.TempHistoryDataDaoManager;
import com.jstyle.jclifexd.model.HealthData;
import com.jstyle.jclifexd.model.TemperatureHistoryData;
import com.jstyle.jclifexd.utils.ChartDataUtil;
import com.jstyle.jclifexd.utils.DateUtil;
import com.jstyle.jclifexd.utils.HealthDataUtils;
import com.jstyle.jclifexd.utils.ResolveData;
import com.jstyle.jclifexd.utils.ScreenUtils;

import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import lecho.lib.hellocharts.view.LineChartView;

public class TempHistoryActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.bt_goal_back)
    Button btGoalBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.rb_history_week)
    RadioButton rbHistoryWeek;
    @BindView(R.id.rb_history_month)
    RadioButton rbHistoryMonth;
    @BindView(R.id.rb_history_year)
    RadioButton rbHistoryYear;
    @BindView(R.id.rg_history)
    RadioGroup rgHistory;
    @BindView(R.id.bt_data_month_preMonth)
    ImageView btDataMonthPreMonth;
    @BindView(R.id.bt_data_month_date)
    Button btDataMonthDate;
    @BindView(R.id.bt_data_month_nextMonth)
    ImageView btDataMonthNextMonth;
    @BindView(R.id.ColumnChartView_history)
    LineChartView ColumnChartViewHistory;
    @BindView(R.id.RecyclerView_historyTempTotal)
    RecyclerView RecyclerViewHistoryTempTotal;
    @BindView(R.id.bt_history_dataType)
    Button btHistoryDataType;
    @BindView(R.id.RecyclerView_historyTemp)
    RecyclerView RecyclerViewHistoryTemp;
    @BindView(R.id.ll_child)
    LinearLayout llChild;
    @BindView(R.id.ll_scrollView)
    NestedScrollView llScrollView;
    @BindView(R.id.tv_noData)
    TextView tvNoData;
    private String thisMonth;
    private String[] monthDates;
    private String[] thisWeek;
    String queryDate;
    private int year;
    public int dateType = 0;
    public final static int dateDay = 0;
    public final static int dateWeek = 1;
    public final static int dateMonth = 2;
    public final static int dateYear = 3;
    public final static int Operation_Pre = 0;
    public final static int Operation_Next = 1;
    public final static int Operation_Show = 2;
    public int Operation = Operation_Pre;
    @BindArray(R.array.temp_totalArray)
    String[] arrayTotal;
    private TempTotalAdapter historyShowAdapter;
    private List<TemperatureHistoryData> healthDataList;
    HashMap<String, List<Float>> dateHashMap = new HashMap<>();
    private boolean isBusy;
    private TempHistoryDetailAdapter tempHistoryDetailAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temp_history);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        btGoalBack.setText(R.string.temperature);
        queryDate = DateUtil.getDefaultFormatTime(new Date());
        Calendar calendar = Calendar.getInstance();
        thisMonth = DateUtil.getMonthString("", DateUtil.this_month);
        monthDates = DateUtil.getThisMonth();
        thisWeek = DateUtil.getTodayWeek(0);
        rgHistory.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_history_week:
                        dateType = dateDay;
                        findTempData(queryDate);
                        break;
                    case R.id.rb_history_month:
                        dateType = dateWeek;
                        findData(thisWeek[0], thisWeek[6], thisWeek);
                        break;
                    case R.id.rb_history_year:
                        dateType = dateMonth;
                        findData(monthDates[0], monthDates[monthDates.length - 1], monthDates);
                        break;
                }
                btDataMonthDate.setText(currentShowDate[dateType]);
                btDataMonthNextMonth.setEnabled(enableState[dateType]);
            }
        });

        currentShowDate[dateDay] = DateUtil.getShowDay(this, queryDate);
        currentShowDate[dateWeek] = DateUtil.getShowWeekDate(this, thisWeek[0]) + "-" + DateUtil.getShowWeekDate(this, thisWeek[6]);
        currentShowDate[dateMonth] = DateUtil.getShowMonthDate(this, monthDates[0]);
        btDataMonthDate.setText(currentShowDate[dateType]);
        GridLayoutManager layoutManager2 = new GridLayoutManager(this, 3);
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);

        historyShowAdapter = new TempTotalAdapter(Arrays.asList(arrayTotal));
        RecyclerViewHistoryTempTotal.setAdapter(historyShowAdapter);
        RecyclerViewHistoryTempTotal.setLayoutManager(layoutManager2);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        tempHistoryDetailAdapter = new TempHistoryDetailAdapter();
        RecyclerViewHistoryTemp.setLayoutManager(linearLayoutManager);
        RecyclerViewHistoryTemp.setAdapter(tempHistoryDetailAdapter);
        RecyclerView.ItemDecoration itemDecoration=new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);

        RecyclerViewHistoryTemp.addItemDecoration(itemDecoration);
        rgHistory.check(R.id.rb_history_week);

    }

    @OnClick({R.id.iv_back, R.id.iv_share, R.id.bt_data_month_preMonth, R.id.bt_data_month_nextMonth})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_share:
                ScreenUtils.shareFile(this, llScrollView);
                break;
            case R.id.bt_data_month_preMonth:

                showDate(Operation_Pre);
                break;
            case R.id.bt_data_month_nextMonth:
                showDate(Operation_Next);

                break;
        }
    }

    private String[] currentShowDate = new String[3];
    boolean[]enableState=new boolean[3];
    private void showDate(int operation) {
        Operation = operation;
        String showDate = "";
        switch (dateType) {
            case dateDay:
                String nowDateT = DateUtil.getDefaultFormatTime(new Date());
                queryDate = operation == Operation_Next ? DateUtil.getTomorrowDateString(queryDate) : DateUtil.getYesterdayDateString(queryDate);
                btDataMonthNextMonth.setEnabled(!queryDate.equals(nowDateT));
                showDate = DateUtil.getShowDay(this, queryDate);
                findTempData(queryDate);
                break;
            case dateWeek:
                String nowDate = DateUtil.getDefaultFormatTime(new Date());
                thisWeek = operation == Operation_Next ? DateUtil.getWeekString(thisWeek[6], DateUtil.nextWeek) : DateUtil.getWeekString(thisWeek[0], DateUtil.lastWeek);
                btDataMonthNextMonth.setEnabled(true);
                if (operation == Operation_Next) {
                    in:for (int i = 0; i < thisWeek.length - 1; i++) {
                        if (thisWeek[i].equals(nowDate)) {
                            btDataMonthNextMonth.setEnabled(false);
                            break in;
                        }
                    }
                }
                showDate = DateUtil.getShowWeekDate(this, thisWeek[0]) + "-" + DateUtil.getShowWeekDate(this, thisWeek[6]);
                findData(thisWeek[0], thisWeek[6], thisWeek);
                break;
            case dateMonth:
                thisMonth = operation == Operation_Next ? DateUtil.getMonthString(thisMonth, DateUtil.next_month) : DateUtil.getMonthString(thisMonth, DateUtil.last_month);
                monthDates = operation == Operation_Next ? DateUtil.getNextMonth(monthDates[0]) : DateUtil.getLastMonth(monthDates[0]);
                showDate = DateUtil.getShowMonthDate(this, monthDates[0]);
                findData(monthDates[0], monthDates[monthDates.length - 1], monthDates);
                btDataMonthNextMonth.setEnabled(DateUtil.monthEnable(this, showDate));

                break;

        }
        btDataMonthDate.setText(showDate);
        currentShowDate[dateType] = showDate;
        enableState[dateType]=btDataMonthNextMonth.isEnabled();
        // showDate(showDate, baseFragment);
    }

    private void findTempData(String startDate) {
        List<TemperatureHistoryData> healthDataList = TempHistoryDataDaoManager.queryDayData(startDate);
        initChartView(healthDataList, startDate);
    }

    /**温度折线图（天，取每小时平均值）
     * @param healthDataList
     * @param queryDate
     */
    private void initChartView(List<TemperatureHistoryData> healthDataList, String queryDate) {
        float count = 0;
        float totalDayHr = 0;
        float maxDayHr = 0;
        float minDayHr = 300;
        float[] healthArray = new float[1440];
        List<TemperatureHistoryData> healthDataTemp = new ArrayList<>();
        int[]tempCount=new int[3];
        for (int i = 0; i < healthDataList.size(); i++) {
            TemperatureHistoryData temperatureHistoryData = healthDataList.get(i);
            float data = temperatureHistoryData.getTempValue();
            //    if(data==0)healthDataTemp.add(heartData);
            String date = temperatureHistoryData.getTime();
            int startCount = DateUtil.get1MIndex(date, queryDate + " 00:00:00");
            //  int heartRate = ResolveData.getData(heartData, dateType);
            if (data != 0) {
                count++;
                totalDayHr += data;
                maxDayHr = Math.max(maxDayHr, data);
                minDayHr = Math.min(minDayHr, data);
                tempCount[HealthDataUtils.getTempLevel(data)]++;
            }
            healthArray[startCount] = data;
        }
        healthDataList.removeAll(healthDataTemp);
        float avgHR = count == 0 ? 0 : totalDayHr / count;
        float[] maxHeartArray = new float[24];
        for (int i = 0; i < 24; i++) {
            int start = i * 60;
            float totalHr = 0;
            float countHr = 0;
            for (int j = 0; j < 60; j++) {//每小时的平均值
                float hr = healthArray[j + start];
                if (hr != 0) {
                    totalHr += hr;
                    countHr++;
                }
            }
            maxHeartArray[i] = countHr == 0 ? 0 : totalHr / countHr;
        }
        if (count == 0) {

            ColumnChartViewHistory.setVisibility(View.GONE);
            // LineChartViewHistory.setVisibility(View.GONE);
            tvNoData.setVisibility(View.VISIBLE);
        } else {
            ColumnChartViewHistory.setVisibility(View.VISIBLE);
            //   LineChartViewHistory.setVisibility(dataType==HealthHistoryActivity.DATA_BLOOD?View.GONE:View.VISIBLE);
            tvNoData.setVisibility(View.GONE);

        }
        float top = (maxDayHr / 10 + 1) * 10;
        ChartDataUtil.initDataChartView(ColumnChartViewHistory, -0.5f, 46, 24.5f, 25);
        ColumnChartViewHistory.setLineChartData(ChartDataUtil.getHealthTempLineChart(maxHeartArray, top));
        setTotalAdapter(avgHR, maxDayHr, minDayHr);
        setDetailAdapter(tempCount);
    }

    private static final String TAG = "TempHistoryActivity";

    /**周 月数据
     * @param startDate
     * @param endDate
     * @param dateArray
     */
    private void findData(final String startDate, final String endDate, final String[] dateArray) {
        dateHashMap.clear();
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                healthDataList = TempHistoryDataDaoManager.queryYearData(startDate, endDate);
                //lastHealthData = healthDataList.size() == 0 ? new HealthData() : healthDataList.get(0);
                initTempData(healthDataList);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer value) {
                Log.i(TAG, "onNext: " + value);
            }

            @Override
            public void onError(Throwable e) {

                isBusy = false;
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {

                setWeekHealthViewData(dateArray);
                isBusy = false;
            }
        });

    }

    /**温度折线图（周月，每天平均值）
     * @param dateArray
     */
    private void setWeekHealthViewData(String[] dateArray) {
        float max = 0;
        float min = 300;
        HashMap<String, Float> weekMap = new HashMap<>();
        float totalWeek = 0;
        float size = 0;
        int[]tempCount=new int[3];
        for (String date : dateArray) {
            List<Float> list = dateHashMap.get(date);
            if (list != null) {
                size += list.size();
                float totalDay = 0;
                for (Float i : list) {
                    max = Math.max(i, max);
                    min = Math.min(i, min);
                    totalDay += i;
                    tempCount[HealthDataUtils.getTempLevel(i)]++;
                }
                float value = totalDay / list.size();
                weekMap.put(date, value);//每天取平均值
                totalWeek += totalDay;
            }

        }

        ColumnChartViewHistory.setVisibility(totalWeek == 0 ? View.GONE : View.VISIBLE);
        tvNoData.setVisibility(totalWeek == 0 ? View.VISIBLE : View.GONE);

        ChartDataUtil.initDataChartView(ColumnChartViewHistory, -0.5f, 46, dateArray.length, 25);
        ColumnChartViewHistory.setLineChartData(ChartDataUtil.getTempWeekLineChart(this, weekMap, dateArray));
        float avgHR = size == 0 ? 0 : totalWeek / size;
        setTotalAdapter(avgHR, max, min);
        setDetailAdapter(tempCount);
    }

    /**数据统计占比
     * @param tempCount
     */
    private void setDetailAdapter(int []tempCount) {
        tempHistoryDetailAdapter.setData(tempCount);
    }

    /**总数据
     * @param avgHR
     * @param max
     * @param min
     */
    private void setTotalAdapter(float avgHR, float max, float min) {
        List<String> listHeart = new ArrayList<>();//总计列表
        NumberFormat numberFormat = ResolveData.getNumberFormat(1);
        numberFormat.setRoundingMode(RoundingMode.DOWN);
        listHeart.add(avgHR==0?"--":numberFormat.format(avgHR)+"℃");
        listHeart.add(max==0?"--": max+"℃");
        listHeart.add((min == 300 ? "--" : min+"℃"));
        historyShowAdapter.setStepData(listHeart);
    }

    private void initTempData(List<TemperatureHistoryData> healthDataList) {

        for (TemperatureHistoryData healthData : healthDataList) {
            String time = healthData.getTime();
            String[] timeArray = time.split(" ");
            String date = timeArray[0];

            List<Float> list = dateHashMap.get(date);
            float value = healthData.getTempValue();
            if (value != 0) {
                if (list == null) {
                    list = new ArrayList<>();
                }
                list.add(value);
                dateHashMap.put(date, list);
            }
        }
    }


}
